package com.physics.mps.entity.annotation;

import com.physics.mps.entity.dto.AppParamEntity;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author mcsoft
 * @date 2023/09/18 14:31
 **/
public class AppParamValidator implements ConstraintValidator<ValidAppParam, AppParamEntity> {

    @Override
    public void initialize(ValidAppParam constraintAnnotation) {

    }

    @Override
    public boolean isValid(AppParamEntity entity, ConstraintValidatorContext context) {
        if (entity.getType() == null) {
            return false;
        }

        switch (entity.getType()) {
            case 0:
                if (entity.getValue() == null || entity.getValue().trim().isEmpty()) {
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate("When type is 0, value cannot be empty.")
                            .addPropertyNode("value").addConstraintViolation();
                    return false;
                }
                entity.setValueList(null);
                entity.setValueMap(null);
                break;
            case 1:
                if (entity.getValueList() == null || entity.getValueList().trim().isEmpty()) {
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate("When type is 1, valueList cannot be empty.")
                            .addPropertyNode("valueList").addConstraintViolation();
                    return false;
                }
                entity.setValue(null);
                entity.setValueMap(null);
                break;
            case 2:
                if (entity.getValueMap() == null || entity.getValueMap().trim().isEmpty()) {
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate("When type is 2, valueMap cannot be empty.")
                            .addPropertyNode("valueMap").addConstraintViolation();
                    return false;
                }
                entity.setValue(null);
                entity.setValueList(null);
                break;
            default:
                return false;
        }
        return true;
    }
}
